import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import 'element-plus/dist/index.css'
import ElementPlus from 'element-plus'

import getCookie from './utils/utils'

axios.defaults.baseURL = ''

const token = localStorage.getItem('token');
if (token) {
  axios.defaults.headers.common['Authorization'] = `Token ${token}`;
}

axios.defaults.withCredentials = true;

axios.interceptors.request.use(config => {
  // 只为 'POST', 'PUT', 'DELETE', 'PATCH' 等不安全方法添加CSRF token
  // 或者更简单：如果不是 'GET', 'HEAD', 'OPTIONS'
  const unsafeMethods = /^(POST|PUT|DELETE|PATCH)$/i;
  if (unsafeMethods.test(config.method.toUpperCase())) {
    const csrfToken = getCookie('csrftoken');
    if (csrfToken) {
      config.headers['X-CSRFToken'] = csrfToken;
    } else {
      console.warn('CSRF token not found in cookies. Request might fail.');
    }
  }
  return config;
}, error => {
  return Promise.reject(error);
});

const app = createApp(App)
app.use(router)
app.use(ElementPlus)
app.mount('#app')
